<template>
    <div>
        <div class="page-comon-header">
            <div class="left">
                <label class="font14 margin-r-5">筛选</label>
                <el-select
                    v-model="search.type"
                    clearable
                    @change="handleSelectChange"
                    placeholder="请选择">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </div>
            <div class="right">
                <div class="right-item text-center">
                    <span class="font28 padding-b-10">{{totalSuppliers}}</span>
                    <p class="font14 txt-info">供应商数量</p>
                </div>
            </div>
        </div>
        
        <div class="page-search-bar">
            <div class="left">
                <label class="font14 margin-r-5">搜索供应商</label>
                <el-input
                    placeholder="输入关键词"
                    icon="search"
                    v-model="search.keyword"
                    @change="handleKeywordChange"
                    :on-icon-click="handleIconClick">
                </el-input>
            </div>
            <div class="right">
                <el-badge :value="selectedRows.length" :max="99" class="margin-r-15">
                    <el-button
                        :plain="true"
                        type="danger"
                        @click="handleBatchDelete">批量删除</el-button>
                </el-badge>
                <el-button
                    class="margin-l-15"
                    type="info"
                    icon="refresh"
                    @click="forceRefreshData">刷新数据</el-button>
                <router-link to="/supplier/add">
                    <el-button
                        class="margin-l-15"
                        type="primary">添加供应商</el-button>
                </router-link>
                <router-link to="/supplier/import-export">
                    <el-button
                        class="margin-l-15"
                        type="success">导入/导出</el-button>
                </router-link>
            </div>
        </div>
        
        <el-table
            row-class-name="rowStyle"
            @selection-change="handleSelectionChange"
            :data="tableData" stripe style="width: 100%">
            <el-table-column
                type="selection"
                align="center"
                width="55">
            </el-table-column>
            <el-table-column
                prop="name"
                label="公司名称">
            </el-table-column>
            <el-table-column
                prop="code"
                label="简称">
            </el-table-column>
            <el-table-column
                prop="business_scope"
                label="主营业务">
            </el-table-column>
            <el-table-column
                prop="phone"
                label="联系方式">
            </el-table-column>
            <el-table-column
                prop="address"
                label="总部地址">
            </el-table-column>
            <el-table-column
                label="成立时间">
                <template slot-scope="scope">
                    {{ formatDate(scope.row.found_time) }}
                </template>
            </el-table-column>
            <el-table-column
                prop="action"
                label="操作">
                <template scope="scope">
                    <el-button 
                        size="small"
                        :plain="true"
                        @click="handleDetail(scope.$index, scope.row)">详情</el-button>
                    <el-button
                        size="small"
                        :plain="true"
                        type="primary"
                        style="margin-left: 0;" 
                        @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button
                        size="small"
                        :plain="true"
                        type="danger"
                        style="margin-left: 0;"
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-bar margin-t-15" v-show="pagination.total > 10">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            layout="total, prev, pager, next"
            :total="pagination.total">
          </el-pagination>
        </div>
    </div>
</template>

<script>
import axios from 'axios';

// 设置全局axios基本配置
axios.defaults.baseURL = 'http://localhost:5000';
axios.defaults.headers.common['Cache-Control'] = 'no-cache, no-store, must-revalidate';
axios.defaults.headers.common['Pragma'] = 'no-cache';
axios.defaults.headers.common['Expires'] = '0';
axios.defaults.timeout = 10000; // 10秒超时

export default {
    data() {
        return {
            // 搜索字段
            search: {
                type: '',
                keyword: '',
                page: 1,
            },
            
            // 是否加载中
            loading: false,
            
            // 选择的行
            selectedRows: [],
            
            // 选择业务类型列表
            options: [{
                value: '全部',
                label: '全部类型'
            }, {
                value: '原材料',
                label: '原材料供应商'
            }, {
                value: '加工',
                label: '加工服务商'
            }, {
                value: '包装',
                label: '包装供应商'
            }, {
                value: '物流',
                label: '物流服务商'
            }],
            
            // 表格数据
            tableData: [],
            
            // 分页器数据
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0,
            },

            // 供应商总数
            totalSuppliers: 0
        }
    },
    
    created() {
        // 强制刷新数据，避免缓存
        this.forceRefreshData();
    },
    
    // 添加路由守卫，确保每次进入页面都刷新数据
    beforeRouteEnter(to, from, next) {
        next(vm => {
            // 强制刷新数据
            vm.forceRefreshData();
        });
    },
    
    methods: {
        // 强制刷新数据，避免缓存
        forceRefreshData() {
            // 清空本地数据
            this.tableData = [];
            this.pagination.total = 0;
            this.totalSuppliers = 0;
            
            // 清除浏览器缓存
            this.clearBrowserCache();
            
            // 首先检查网络连接
            this.checkNetworkConnection()
                .then(isConnected => {
                    if (isConnected) {
                        // 获取最新数据
                        this.getSupplierList();
                    } else {
                        this.$message.error('网络连接异常，请检查您的网络连接');
                    }
                });
        },
        
        // 检查网络连接
        checkNetworkConnection() {
            return new Promise(resolve => {
                // 检查网络连接是否可用
                if (!navigator.onLine) {
                    console.error('浏览器离线状态');
                    resolve(false);
                    return;
                }
                
                // 尝试简单请求
                axios.get('/api/ping', {
                    timeout: 3000,
                    headers: {
                        'Cache-Control': 'no-cache',
                        'Pragma': 'no-cache',
                        'Expires': '0'
                    }
                })
                .then(() => {
                    console.log('网络连接正常');
                    resolve(true);
                })
                .catch(err => {
                    console.error('网络连接检查失败:', err);
                    // 即使请求失败，也继续尝试加载数据
                    resolve(true);
                });
            });
        },
        
        // 清除浏览器缓存
        clearBrowserCache() {
            // 清除localStorage中的相关数据
            try {
                // 清除可能存在的缓存数据
                localStorage.removeItem('supplier_data');
                localStorage.removeItem('supplier_total');
                
                // 打印日志
                console.log('已清除浏览器缓存数据');
            } catch (e) {
                console.error('清除缓存出错:', e);
            }
        },
        
        // 获取供应商列表
        getSupplierList() {
            this.loading = true;
            
            // 清空之前的数据，避免累加
            this.tableData = [];
            
            // 记录请求时间
            console.time('加载供应商数据');
            
            // 生成随机数，确保每次请求都是新的
            const randomParam = Math.random();
            
            // 设置超时时间和重试
            const axiosConfig = {
                params: {
                    page: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize,
                    keyword: this.search.keyword,
                    type: this.search.type,
                    _t: new Date().getTime(), // 时间戳
                    _r: randomParam // 随机数
                },
                headers: {
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0'
                },
                timeout: 10000 // 10秒超时
            };
            
            // 调用后端API获取供应商列表，添加时间戳和随机参数避免缓存
            axios.get('/api/suppliers', axiosConfig)
            .then(response => {
                if (response.data.status === 'success') {
                    // 直接赋值而不是追加
                    this.tableData = response.data.items || [];
                    this.pagination.total = response.data.total || 0;
                    this.totalSuppliers = response.data.total || 0;
                    
                    // 打印日志方便调试
                    console.log(`加载了${this.tableData.length}条供应商数据，总数：${this.totalSuppliers}`);
                    console.log('首条数据示例:', this.tableData.length > 0 ? this.tableData[0] : null);
                    console.timeEnd('加载供应商数据');
                } else {
                    this.$message.error(response.data.message || '获取供应商列表失败');
                    console.error('API返回错误:', response.data);
                }
            }).catch(err => {
                console.error('获取供应商列表出错:', err);
                let errorMsg = '获取供应商列表失败';
                
                if (err.response) {
                    // 服务器返回了错误状态码
                    errorMsg += `: 服务器错误 (${err.response.status})`;
                    console.error('错误响应数据:', err.response.data);
                } else if (err.request) {
                    // 请求发送了但没有收到响应
                    errorMsg += ': 无法连接到服务器，请检查后端服务是否运行';
                    console.error('无响应:', err.request);
                } else {
                    // 请求设置时出错
                    errorMsg += `: ${err.message || err}`;
                }
                
                this.$message.error(errorMsg);
            }).finally(() => {
                this.loading = false;
            });
        },
        
        handleSelectChange(value) {
            this.search.type = value;
            this.getSupplierList();
        },
        
        handleCurrentChange(page) {
            this.pagination.currentPage = page;
            this.search.page = page;
            this.getSupplierList();
        },
        
        handleDelete(index, row) {
            this.$confirm('确认删除该供应商?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 实际调用
                axios.delete('/api/suppliers/' + row.id).then(response => {
                    if (response.data.status === 'success') {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getSupplierList();
                    } else {
                        this.$message.error(response.data.message || '删除失败');
                    }
                }).catch(err => {
                    console.error('删除请求失败:', err);
                    this.$message.error('删除操作失败，请检查网络连接');
                });
                
                // 模拟成功删除
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.getSupplierList();
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        
        handleKeywordChange(value) {
            this.search.keyword = value;
        },
        
        handleIconClick(e) {
            this.getSupplierList();
        },
        
        handleDetail(index, row) {
            this.$router.push({
                path: '/supplier/detail',
                query: { id: row.id }
            });
        },
        
        handleEdit(index, row) {
            this.$router.push({
                path: '/supplier/edit',
                query: { id: row.id }
            });
        },
        
        handleSelectionChange(val) {
            this.selectedRows = val;
        },
        
        handleBatchDelete() {
            if (this.selectedRows.length === 0) {
                this.$message({
                    type: 'warning',
                    message: '请选择要删除的供应商'
                });
                return;
            }
            
            this.$confirm(`确认删除选中的 ${this.selectedRows.length} 个供应商?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 实际调用
                const ids = this.selectedRows.map(row => row.id);
                axios.post('/api/suppliers/batch-delete', { ids }).then(response => {
                    if (response.data.status === 'success') {
                        this.$message({
                            type: 'success',
                            message: response.data.message || '批量删除成功!'
                        });
                        this.getSupplierList();
                    } else {
                        this.$message.error(response.data.message || '批量删除失败');
                    }
                }).catch(err => {
                    if (err.response && err.response.data && err.response.data.message) {
                        this.$message.error(err.response.data.message);
                    } else {
                        console.error('批量删除供应商失败:', err);
                        this.$message.error('批量删除供应商失败');
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        
        formatDate(date) {
            if (!date) return '-';
            try {
                const dateObj = new Date(date);
                if (isNaN(dateObj.getTime())) {
                    return '-'; // 日期无效
                }
                // 如果日期是1月1日，说明只有年份信息
                if (dateObj.getMonth() === 0 && dateObj.getDate() === 1) {
                    return dateObj.getFullYear() + '年';
                }
                return dateObj.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit'
                }).replace(/\//g, '-');
            } catch (e) {
                console.error('日期格式化错误:', e, date);
                return '-';
            }
        }
    }
}
</script>

<style scoped>
    .right-item {
        padding-right: 50px;
    }
    .pagination-bar {
        display: flex;
        justify-content: center;
    }
    .rowStyle {
        height: 50px;
    }
    
    .page-search-bar .left {
        display: flex;
        align-items: center;
    }
    .page-search-bar .left label {
        width: 80px;
    }
    
    .page-search-bar .right {
        display: flex;
        align-items: center;
    }
</style>